const request = indexedDB.open("multiple", 4);

request.onupgradeneeded = function (event) {
    const db = event.target.result;

    try {
        db.deleteObjectStore("books");
    } catch (error) {
        console.log("deleteObjectStore err", error);
    }

    try {
        db.deleteObjectStore("users");
    } catch (error) {
        console.log("deleteObjectStore err", error);
    }

    const bookStore = db.createObjectStore("books", { keyPath: "id" });
    bookStore.createIndex("title", "title", { unique: true });
    bookStore.createIndex("userIdIndex", "userId", { unique: false });

    const userStore = db.createObjectStore("users", { keyPath: "id" });
    userStore.createIndex("name", "name", { unique: false });
};

request.onsuccess = function (event) {
    const db = event.target.result;

    // 联合查询示例：根据用户ID查询该用户借阅的书籍
    function findBooksByUserId(userId) {

        // 多表事务
        const transaction = db.transaction(["books", "users"], "readonly");

        // 多个对象存储
        const bookStore = transaction.objectStore("books");
        const userStore = transaction.objectStore("users");

        // 准备通过索引发起查询
        const userIdIndex = bookStore.index("userIdIndex");

        // 查询唯一用户
        const userRequest = userStore.get(userId);
        userRequest.onsuccess = function (event) {
            const user = event.target.result;

            if (user) {
                const books = [];

                // only = [id] = 指定查询范围为单个id
                // lowerBoun = [id,max]
                // upperBound = [min,id]
                // bound = [start,end]
                const keyRange = IDBKeyRange.only(user.id);

                // 根据范围查询索引表
                const booksRequest = userIdIndex.openCursor(keyRange);

                // 这个查询会被反复调用 直到上述范围穷尽
                booksRequest.onsuccess = function (event) {
                    const cursor = event.target.result;
                    console.log("new cursor=", cursor);

                    if (cursor) {
                        const book = cursor.value;
                        books.push(book);
                        cursor.continue();
                    } else {
                        // 运行到这 就说明再也没有新的cursor了
                        console.log(`用户 ${user.name} 借阅的书籍：`, books);
                    }

                };

            } else {
                console.log("未找到匹配的用户");
            }
        };

        transaction.oncomplete = function (event) {
            console.log("事务完成");
        };

        transaction.onerror = function (event) {
            console.log("事务发生错误", event.target.error);
        };
    }

    // 示例数据
    const booksData = [
        { id: "1", title: "Book 1", userId: "123" },
        { id: "2", title: "Book 2", userId: "456" },
        { id: "3", title: "Book 3", userId: "123" },
        { id: "4", title: "Book 4", userId: "789" }
    ];

    const usersData = [
        { id: "123", name: "Alice" },
        { id: "456", name: "Bob" },
        { id: "789", name: "Charlie" }
    ];

    // 添加示例数据到数据库
    function addSampleData() {
        const transaction = db.transaction(["books", "users"], "readwrite");
        const bookStore = transaction.objectStore("books");
        const userStore = transaction.objectStore("users");

        for (const book of booksData) {
            bookStore.add(book);
        }
        for (const user of usersData) {
            userStore.add(user);
        }

        transaction.oncomplete = function (event) {
            console.log("示例数据添加完成");
        };

        transaction.onerror = function (event) {
            console.log("事务发生错误", event.target.error);
            try {
                transaction.abort();
            } catch (error) {
                console.log("error=", error);
            }

        };
    }

    // 调用示例操作
    addSampleData();

    findBooksByUserId("123"); // 根据用户ID查询该用户借阅的书籍
};